package ru.urfc.portal.ui.client.controllers;

import ru.urfc.portal.ui.client.Utils;

import com.extjs.gxt.ui.client.data.HttpProxy;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.google.gwt.http.client.RequestBuilder;

public class RestProxy extends HttpProxy<PagingLoadResult<ModelData>> {

	private String requestData;

	public RestProxy(RequestBuilder requestBuilder) {
		super(requestBuilder);
	}

	@Override
	protected String generateUrl(Object loadConfig) { // Yes it is quick dirty hack
		if (builder.getHTTPMethod().toLowerCase().matches("(post)|(put)")) {
			return requestData;
		}
		return super.generateUrl(loadConfig);
	}
	
	public RestProxy setRequestData(String requestData) {
		this.requestData = requestData;
		return this;
	}

	public static RestProxy create(String url, String httpMethod) {
		RequestBuilder requestBuilder;
		if (httpMethod.equals("POST")) {
			requestBuilder = Utils.createPostRequestBuilder(url);
		} else if (httpMethod.equals("PUT")) {
			requestBuilder = Utils.createPutRequestBuilder(url);
		} else if (httpMethod.equals("DELETE")) {
			requestBuilder = Utils.createDeleteRequestBuilder(url);
		} else {
			requestBuilder = Utils.createGetRequestBuilder(url);
		}
		return new RestProxy(requestBuilder);
	}

}
